﻿
using System.Buffers;


namespace Geek.Server.Core.Net.Tcp
{
    public abstract class BaseDispatcher
    {
       
        protected const int MAX_RECV_SIZE = 1024 * 1024 * 5; /// 从客户端接收的包大小最大值（单位：字节 5M）

        protected static readonly NLog.Logger LOGGER = NLog.LogManager.GetCurrentClassLogger();

        public NetChannel Channel;
        /// <summary>
        /// 最小接受长度
        /// </summary>
        protected abstract int MinRecvSize { get; }
       
        /// <summary>
        /// 尝试解析
        /// </summary>
        /// <param name="input"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public abstract bool TryParse(ref ReadOnlySequence<byte> input, out object msg);


        public  abstract Task Dispatcher(object obj);

        public abstract Span<byte> ParseToByte(object obj);


        /// <summary>
        /// 检查消息长度是否合法
        /// </summary>
        /// <param name="msgLen"></param>
        /// <returns></returns>
        protected bool CheckMsgLen(int msgLen)
        {
            //消息长度+时间戳+magic+消息id+数据
            //4 + 8 + 4 + 4 + data
            if (msgLen <= MinRecvSize)//(消息长度已经被读取)
            {
                LOGGER.Error("从客户端接收的包大小异常:" + msgLen + ":至少16个字节");
                return false;
            }
            else if (msgLen > MAX_RECV_SIZE)
            {
                LOGGER.Error("从客户端接收的包大小超过限制：" + msgLen + "字节，最大值：" + MAX_RECV_SIZE / 1024 + "字节");
                return false;
            }
            return true;
        }

    }
}
